{% load i18n %}
{% load avatar_tags %}
{% load static from staticfiles %}

{% if is_layer and storeType != "remoteStore" and GEONODE_SECURITY_ENABLED and OGC_SERVER.default.BACKEND == 'geonode.geoserver' %}
<script src="{% static "geonode/js/proj4js/proj4.js" %}" type="text/javascript"></script>
<script src="{% static "geonode/js/ol-2.13/OpenLayers.js" %}" type="text/javascript"></script>
<script src="{% static "geonode/js/ol-2.13/lib/OpenLayers/Layer/ArcGISCache.js" %}" type="text/javascript"></script>
<script src="{% static "geonode/js/ol-2.13/ext/geonode_ol_ext.js" %}" type="text/javascript"></script>
<script src="{% static "geonode/js/jszip/jszip.js" %}" type="text/javascript"></script>
<script src="{% static "geonode/js/jszip/jszip-utils.js" %}" type="text/javascript"></script>
<script src="{% static "geonode/js/jszip/preprocess.js" %}" type="text/javascript"></script>
<script src="{% static "geonode/js/jszip/preview.js" %}" type="text/javascript"></script>

<style>
    /* Bootstrap */
    .modal {
      overflow: auto !important;
    }
    .tooltip {
      position: fixed;
    }
    .bt-scrollable {
      max-height: 180px;
      margin-bottom: 10px;
      overflow:scroll;
      -webkit-overflow-scrolling: touch;
    }
    .photo {
      border-radius: 45px;
      margin-right: 10px;
      width: 64px;
      height:64px
    }
    .name {
      font-weight: 700;
    }
    .expertise-label {
      display:block;
      font-weight: 700;
      margin-top:10px;
    }
    .btn-more {
      margin-top:10px;
      width: 100%
    }
    .label {
      font-weight: normal;
    }
    #dataInfo {
      text-align: center;
    }
    #option {
      display: none;
    }

    /* OpenLayers */
    .olControlAttribution {
        bottom: 0 !important;
    }
    .olControlEditingToolbar .olControlRemoveFeatureItemInactive{
        background-position: -153px -1px;
    }
    .olControlEditingToolbar .olControlRemoveFeatureItemActive {
        background-position: -153px -24px;
    }
</style>
{% endif %}

<div class="modal fade" id="_permissions" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <form id="permission_form" accept-charset="UTF-8" method="post" class="modal-form" action="{% url "resource_permissions" resource.id %}">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
          <h4 class="modal-title" id="myModalLabel">{% trans "Set permissions for this resource" %}</h4>
        </div>
        <div class="modal-body">
          <div class="tabbable">
            <ul class="nav nav-tabs">
              <li class="active"><a href="#permissions_tab1" data-toggle="tab">{% trans "People and Groups" %}</a></li>
              {% if is_layer and storeType != "remoteStore" and GEONODE_SECURITY_ENABLED and OGC_SERVER.default.BACKEND == 'geonode.geoserver' %}
                {% if user.is_superuser or "change_resourcebase_permissions" in perms_list %}
                  <li><a href="#permissions_tab2" data-toggle="tab">{% trans "Geo Limits" %}</a></li>
                {% endif %}
              {% endif %}
            </ul>
            <div class="tab-content">
              <div class="tab-pane active" id="permissions_tab1">
                {% include "_permissions.html" %}
              </div>
              {% if is_layer and storeType != "remoteStore" and GEONODE_SECURITY_ENABLED and OGC_SERVER.default.BACKEND == 'geonode.geoserver' %}
                {% if user.is_superuser or "change_resourcebase_permissions" in perms_list %}
                  <div class="tab-pane" id="permissions_tab2">
                    <div class="panel-group" id="gis_limits_map" style="height: 344px;width: 544px;"></div>
                    <div class="tabbable">
                      <ul class="nav nav-tabs">
                        <li class="active"><a href="#gis_limits_tab1" data-toggle="tab">{% trans "Users" %}</a></li>
                        <li><a href="#gis_limits_tab2" data-toggle="tab">{% trans "Groups" %}</a></li>
                      </ul>
                      <div class="tab-content">
                        <div class="tab-pane active" id="gis_limits_tab1">

                            <div id="gis-limits-users">
                                <div class="row">
                                  <div class="col-md-12">
                                    <!-- input class="search form-control" placeholder="{% trans "Search" %}" / -->
                                    <!-- button class="sort btn btn-primary" data-sort="gis-limits-user-name">Sort by name</button -->
                                    <!-- button class="sort btn btn-primary" data-sort="gis-limits-user-title">Sort by title</button -->
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-md-12">
                                    <div id="gis-limits-users-content" class="list-group list bt-scrollable" style="min-height: 200px; height: 500px; overflow-y: scroll">
                                        <span id="gis-limits-users-list">
                                    </div>
                                  </div>
                                </div>
                            </div>

                        </div>
                        <div class="tab-pane" id="gis_limits_tab2">

                            <div id="gis-limits-groups">
                                <div class="row">
                                  <div class="col-md-12">
                                    <input class="search form-control" placeholder="{% trans "Search" %}" />
                                    <!-- button class="sort btn btn-primary" data-sort="gis-limits-group-name">Sort by name</button -->
                                    <!-- button class="sort btn btn-primary" data-sort="gis-limits-group-title">Sort by title</button -->
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-md-12">
                                    <div class="list-group list bt-scrollable">

                                      {% for group in groups %}
                                      <a href="javascript:void(0)" class="list-group-item">
                                      <div class="col-md-8">
                                        <img src="{{ group.logo_url }}" class="pull-left photo">
                                        <h4 class="list-group-item-heading gis-limits-group-name">{{ group.title }}</h4>
                                        <p class="list-group-item-text gis-limits-group-title">{{ group.description }}</p>
                                      </div>
                                      <div class="col-md-4">
                                        <div class="expertise">
                                          <div class="read-more pull-right">
                                            <button id="group-load{{ group.id }}" type="button" class="btn btn-default btn-sm deserialize-geo-limit"
                                              data-toggle="tooltip" data-placement="top" title="{% trans "Show Geo Limits" %}" aria-pressed="true">
                                              <span class="glyphicon glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span>
                                            </button>
                                            <button id="group-upload{{ group.id }}" type="button" class="btn btn-default btn-sm"
                                              data-toggle="tooltip" data-placement="top" title="{% trans "Upload Geo Limits" %}" aria-pressed="true">
                                              <span class="glyphicon glyphicon glyphicon glyphicon-open-file"
                                                    data-toggle="modal" data-target="#_add_shp_zip" aria-hidden="true"></span>
                                            </button>
                                            <button id="group-save{{ group.id }}" type="button" class="btn btn-default btn-sm serialize-geo-limit"
                                              data-toggle="tooltip" data-placement="top" title="{% trans "Save Geo Limits" %}" aria-pressed="true">
                                              <span class="glyphicon glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>
                                            </button>
                                            <button id="group-remove{{ group.id }}" type="button" class="btn btn-default btn-sm delete-geo-limit"
                                              data-toggle="tooltip" data-placement="top" title="{% trans "Delete Geo Limits" %}" aria-pressed="true">
                                              <span class="glyphicon glyphicon glyphicon-trash" aria-hidden="true"></span>
                                            </button>
                                          </div>
                                        </div>
                                      </div>
                                      <div class="clearfix"></div>
                                      </a>
                                      {% endfor %}

                                    </div>
                                  </div>
                                </div>
                            </div>

                        </div>
                      </div>
                    </div>
                  </div>
                {% endif %}
              {% endif %}
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <a href="#" class="btn btn-default" data-dismiss="modal">{% trans "Cancel" %}</a>
          <a href="#" class="btn btn-primary" data-dismiss="modal" id="perms_submit">{% trans "Apply Changes" %}</a>
        </div>
      </div>
    </div>
  </form>
</div>

<div class="modal fade" id="_permissions_feedbacks" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">{% trans "Message box" %}</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">{% trans "OK" %}</button>
      </div>
    </div>
  </div>
</div>

{% if is_layer and storeType != "remoteStore" and GEONODE_SECURITY_ENABLED and OGC_SERVER.default.BACKEND == 'geonode.geoserver' %}
<div id="_add_shp_zip" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">

              <div class="form-group">
                <div class="input-group input-file" name="zipfile" id="zipfile" data-toggle="tooltip" data-placement="bottom" 
                      data-content="{% trans "Mandatory files : SHP , DBF" %}">
                  <span class="input-group-btn">
                    <button id="geo-limits-upload-btn" class="btn btn-default btn-choose" type="button" 
                            data-toggle="tooltip" data-placement="bottom"
                            title="{% trans "Upload a ZIP file containing an ESRI Shapefile. If the ZIP provides also a .prj file, you don't have to specify the EPSG SRID" %}">{% trans "Choose" %}</button>
                  </span>
                  <input id="geo-limits-upload-txt" type="text" class="form-control" 
                         data-toggle="tooltip" data-placement="bottom"
                         title="{% trans "Upload a ZIP file containing an ESRI Shapefile. If the ZIP provides also a .prj file, you don't have to specify the EPSG SRID" %}"
                         placeholder="{% trans "Choose a file..." %}" />
                  <span class="input-group-btn">
                    <button class="btn btn-warning btn-reset" type="button">{% trans "Reset" %}</button>
                  </span>
                </div>
              </div>

              <div class="field" id="dataInfo"></div>

              <div id="option">
                <div class="input-group">
                  <span class="input-group-addon">EPSG</span>
                  <input id="epsg" type="text" class="form-control" name="epsg" 
                         data-toggle="tooltip" data-placement="bottom"
                         title="{% trans "Only the SRID number without the 'EPSG:' prefix!" %}"
                         placeholder="{% trans "Default : 4326" %}" onfocus="this.value='';">
                </div>
                <div class="input-group">
                  <span class="input-group-addon">Encoding</span>
                  <input id="encoding" type="text" class="form-control" name="encoding"
                                       placeholder="{% trans "Set your desired encoding UTF-8, Big5, Big5-HKSCS ..." %}" 
                                       onfocus="this.value='';">
                </div>
                <button type="button" id="loadShpZip" class="btn btn-primary">{% trans "Upload" %}</button>
              </div>

            </div>
            <div class="modal-footer">
              <a href="#" class="btn btn-default" data-dismiss="modal">{% trans "Cancel" %}</a>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function (event) {
    /* Bootstrap */
    $(function () {
      $('[data-toggle="tooltip"]').tooltip()
    })

    var userList = new List('gis-limits-users', {valueNames: ['gis-limits-user-name', 'gis-limits-user-title']});
    var groupList = new List('gis-limits-groups', {valueNames: ['gis-limits-group-name', 'gis-limits-group-title']});
    var limit = 5;
    var offset = 0;
    var lastOffset = 0;
    $(function() {
      load_gis_limits_users();
      $('#gis-limits-users-content').on("scroll", function(event) {
        var scrollHeight = $('#gis-limits-users').height();
        var scrollPosition = $('#gis-limits-users-content').scrollTop();
        if (scrollPosition >= 50*(offset-3)){
          if (offset == lastOffset) {
            offset += limit;
            load_gis_limits_users();
          }
          // event.stopPropagation();
          event.preventDefault();
       }
      });

      function load_gis_limits_users() {
        $.ajax({
          url: "/api/profiles/",
          dataType: 'json',
          data: {
            limit: limit,
            offset: offset,
            order_by: 'username'
          },
          beforeSend: function() {
            $('#loading_icon').show();
          },
          success: function(data) {
            $('#loading_icon').hide();
            users = $(data.objects);
            if (users.length) {
              var html = "";
              users.each(function() {
                userid = $(this)[0].id;
                username = $(this)[0].username;
                avatar = $(this)[0].avatar_100;
                organization = $(this)[0].organization;
                if (organization == null) {
                  organization = "{% trans "No Group" %}";
                }
                html += `
                   <a href="javascript:void(0)" class="list-group-item">
                     <div class="col-md-8">
                       <div class="pull-left photo">
                         <img src="${avatar}" class="pull-left photo">
                       </div>
                       <h4 class="list-group-item-heading gis-limits-user-name">${username}</h4>
                       <p class="list-group-item-text gis-limits-user-title">${organization}</p>
                     </div>
                     <div class="col-md-4">
                       <div class="expertise">
                         <div class="read-more pull-right">
                           <button id="user-load${userid}" type="button" class="btn btn-default btn-sm deserialize-geo-limit"
                             data-toggle="tooltip" data-placement="top" title="{% trans "Show Geo Limits" %}" aria-pressed="true">
                             <span class="glyphicon glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span>
                           </button>
                           <button id="user-upload${userid}" type="button" class="btn btn-default btn-sm"
                             data-toggle="tooltip" data-placement="top" title="{% trans "Upload Geo Limits" %}" aria-pressed="true">
                             <span class="glyphicon glyphicon glyphicon glyphicon-open-file"
                               data-toggle="modal" data-target="#_add_shp_zip" aria-hidden="true"></span>
                           </button>
                           <button id="user-save${userid}" type="button" class="btn btn-default btn-sm serialize-geo-limit"
                             data-toggle="tooltip" data-placement="top" title="{% trans "Save Geo Limits" %}" aria-pressed="true">
                             <span class="glyphicon glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>
                           </button>
                           <button id="user-remove${userid}" type="button" class="btn btn-default btn-sm delete-geo-limit"
                             data-toggle="tooltip" data-placement="top" title="{% trans "Delete Geo Limits" %}" aria-pressed="true">
                             <span class="glyphicon glyphicon glyphicon-trash" aria-hidden="true"></span>
                           </button>
                         </div>
                       </div>
                     </div>
                     <div class="clearfix"></div>
                   </a>`
              });

              if (html) {
                $('#gis-limits-users-list').append(html);
                lastOffset = offset;
                // offset += limit;
              }
            } else {
              $('#warning_area').text("That's all folks!");
            }
          },
          error: function() {
            $('#loading_icon').hide();
            $('#warning_area').text('Unable to load articles, please check your internet connection or try again later.');
            console.log('Ajax Request Has Failed');
          }
        });
      }
    });

    $(".input-file").before(
      function() {
        if ( ! $(this).prev().hasClass('input-ghost') ) {
          var element = $("<input type='file' class='input-ghost' accept='.zip' style='visibility:hidden; height:0'>");
          element.attr("id",$(this).attr("id"));
          element.attr("name",$(this).attr("name"));
          element.change(function(evt){
            element.next(element).find('input').val((element.val()).split('\\').pop());
            file = evt.target.files[0];
            if(file.size > 0) {
              $('#dataInfo').text(' ').append(file.name+' , '+file.size+' kb');
              $('#option').slideDown(500);
            }
          });
          $(this).find("button.btn-choose").click(function(){
            element.click();
          });
          $(this).find("button.btn-reset").click(function(){
            element.val(null);
            $(this).parents(".input-file").find('input').val('');
            $('#dataInfo').text(' ');
            $('#option').slideUp(500);
          });
          $(this).find('input').css("cursor","pointer");
          $(this).find('input').mousedown(function() {
            $(this).parents('.input-file').prev().click();
            return false;
          });
          return element;
        }
      }
    );

    /* OpenLayers */
    {% if resource.ll_bbox %}
      var bbox = [{{ resource.ll_bbox_string }}];
    {% else %}
      var bbox = null;
    {% endif %}
    var source = null;
    {% if resource.ptype == 'gxp_wmscsource' %}
      {% if access_token %}
        var url = '{{ resource.ows_url|safe }}?access_token={{access_token}}';
      {% else %}
        var url = '{{ resource.ows_url|safe }}';
      {% endif %}

      source = new OpenLayers.Layer.WMS("{{ resource.title|safe }}",
        url,
        {layers: '{{ resource.alternate }}', transparent: true},
        {isBaseLayer: false}
      );
    {% elif resource.ptype == 'gxp_arcrestsource' %}
      {% if access_token %}
        var url = '{{ resource.ows_url|safe }}?access_token={{access_token}}';
      {% else %}
        var url = '{{ resource.ows_url|safe }}';
      {% endif %}
        source = new OpenLayers.Layer.ArcGISCache("{{ resource.title|safe }}",
          url,
          {layers: '{{ resource.alternate }}', transparent: true},
          {isBaseLayer: false}
        );
    {% endif %}

    //Snippet comes from http://osgeo-org.1560.x6.nabble.com/OL-2-13-1-latest-Proj4js-td5081636.html
    /* window.Proj4js = {
      Proj: function(code) {
        return proj4(Proj4js.defs[code]);
      },
      defs: proj4.defs,
      transform: proj4
    }; */

    var crs = 'EPSG:4326';  // resource.ll_bbox is always 4326
    if (source != null) {
      var vectors = new OpenLayers.Layer.Vector("Simple Geometry", {
        styleMap: new OpenLayers.StyleMap({'default':{
          strokeColor: "#00FF00",
          strokeOpacity: 1,
          strokeWidth: 3,
          fillColor: "#FF5500",
          fillOpacity: 0.5,
          pointRadius: 6,
          pointerEvents: "visiblePainted",
          // label with \n linebreaks
          // label : "name: ${name}\n\nage: ${age}",
          fontColor: "${favColor}",
          fontSize: "12px",
          fontFamily: "Courier New, monospace",
          fontWeight: "bold",
          labelAlign: "${align}",
          labelXOffset: "${xOffset}",
          labelYOffset: "${yOffset}",
          labelOutlineColor: "white",
          labelOutlineWidth: 3
        }})
      });
    	var layers = [
        new OpenLayers.Layer.OSM("OpenCycleMap",
          ["https://a.tile.openstreetmap.org/${z}/${x}/${y}.png",
            "https://b.tile.openstreetmap.org/${z}/${x}/${y}.png",
            "https://c.tile.openstreetmap.org/${z}/${x}/${y}.png"]),
        source,
        vectors
    	];

    	var map = new OpenLayers.Map({
        div: 'gis_limits_map',
        projection: new OpenLayers.Projection('EPSG:900913'),
        layers: layers,
        center: [0, 0],
        zoom: 2
    	});

      map.addControl(new OpenLayers.Control.EditingToolbar(vectors));

    	if (bbox != null) {
    	  if (crs != 'EPSG:900913') {
          bbox = new OpenLayers.Bounds(bbox).transform(
            new OpenLayers.Projection(crs),
            new OpenLayers.Projection("EPSG:900913"));
        }
    		map.zoomToExtent(bbox);
    	}

      function loadShpZip() {
        var epsg = ($('#epsg').val() == '') ? 4326 : $('#epsg').val(),
        encoding = ($('#encoding').val() == '') ? 'UTF-8' : $('#encoding').val();
        if(file.name.split('.')[1] == 'zip') {
          loadshp({
            url: file,
            encoding: encoding,
            EPSG: epsg
          }, function(data) {
            var geojson_format = new OpenLayers.Format.GeoJSON();
            var features = geojson_format.read(data);
            var features_arr = [];
            for (l=0; l<features.length; l++) {
              var geom = features[l].geometry.clone();
              geom.transform(
                new OpenLayers.Projection("EPSG:" + epsg),
                new OpenLayers.Projection("EPSG:900913"));
              features_arr.push(new OpenLayers.Feature.Vector(geom));
            }
            vectors.removeAllFeatures();
            vectors.addFeatures(features_arr);

            var bbox = new OpenLayers.Bounds(data.bbox).transform(
                new OpenLayers.Projection("EPSG:" + epsg),
                new OpenLayers.Projection("EPSG:900913"));
            map.zoomToExtent(bbox);

            $('#epsg').val('');
            $('#encoding').val('');
            $('#dataInfo').text(' ');
            $('#option').slideUp(500);
            $("#_add_shp_zip").modal("hide");
          });
        } else {
          $('.modal').modal('show');
        }
      }

      $('#loadShpZip').click(function() {
        $("#confirmMsgBoxModalOK").find('.modal-title').html('{% trans "Load SHP-ZIP" %}');
        $("#confirmMsgBoxModalOK").find('.modal-body').html('{% trans "<p>This will remove the Geo Limits currently drawn on the map.</p><p>In order to store the Geo Limits you will need to <strong>save</strong> them anyway.</p><p>Do you want to proceed?</p>" %}');
        $("#confirmMsgBoxModalOK_control_field").val('loadShpZip');
        $('#confirmMsgBoxModalOK').find('.modal-footer .confirm').remove();
        var confirm_button = $('<button />').attr({ type: 'button', id:'confirm_loadShpZip', class:'btn btn-danger confirm' });
        $('#confirmMsgBoxModalOK').find('.modal-footer').append(confirm_button);
        $("#confirmMsgBoxModalOK").modal("show");
        $('#confirm_loadShpZip').html('{% trans "OK" %}');
        $('#confirm_loadShpZip').prop('value', '{% trans "OK" %}');

        $('#confirm_loadShpZip').on('click', function(e) {
          e.stopImmediatePropagation();
          if ($("#confirmMsgBoxModalOK_control_field").val() == 'loadShpZip') {
            $("#confirmMsgBoxModalOK_control_field").val();
            $("#confirmMsgBoxModalOK").modal("hide");
            loadShpZip();
          }
        });
      });

      function serializeGeoLimit(ID) {
        $("#confirmMsgBoxModalOK").find('.modal-title').html('{% trans "Save Geo Limits" %}');
        $("#confirmMsgBoxModalOK").find('.modal-body').html('{% trans "<p>This will override the current stored Geo Limits on the DB.</p><p>To apply them you will need to click on <strong>Apply Changes</strong> button anyway.</p><p><strong>WARNING:</strong> This operation cannot be reverted!</p><p>Do you want to proceed?</p>" %}');
        $("#confirmMsgBoxModalOK_control_field").val('serializeGeoLimit');
        $('#confirmMsgBoxModalOK').find('.modal-footer .confirm').remove();
        var confirm_button = $('<button />').attr({ type: 'button', id:'confirm_serializeGeoLimit', class:'btn btn-danger confirm' });
        $('#confirmMsgBoxModalOK').find('.modal-footer').append(confirm_button);
        $("#confirmMsgBoxModalOK").modal("show");
        $('#confirm_serializeGeoLimit').html('{% trans "OK" %}');
        $('#confirm_serializeGeoLimit').prop('value', '{% trans "OK" %}');

        $('#confirm_serializeGeoLimit').on('click', function(e) {
          e.stopImmediatePropagation();
          if ($("#confirmMsgBoxModalOK_control_field").val() == 'serializeGeoLimit') {
            $("#confirmMsgBoxModalOK_control_field").val();
            $("#confirmMsgBoxModalOK").modal("hide");

            var pretty = false;
            var out_options = {
              'internalProjection': map.projection,
              'externalProjection': new OpenLayers.Projection("EPSG:4326")
            };
            var wkt = new OpenLayers.Format.WKT(out_options);

            var query_param = "";
            if(ID.startsWith("user-save")) {
              query_param = "user_id=" + ID.substring("user-save".length);
            } else if(ID.startsWith("group-save")) {
              query_param = "group_id=" + ID.substring("group-save".length);
            }

            var data = null;
            if (vectors.features.length > 0) {
              var polygonList = [];
              for (i=0;i<vectors.features.length;i++) {
                var polygon = new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(vectors.features[i].geometry.getVertices()));
                polygonList.push(polygon);
              }
              multuPolygonGeometry = new OpenLayers.Geometry.MultiPolygon(polygonList);
              multiPolygonFeature = new OpenLayers.Feature.Vector(multuPolygonGeometry);
              data = wkt.write(multiPolygonFeature, pretty);
            }
            $.ajax({
              type: "POST",
              url: '{% url "resource_geolimits" resource.id %}?' + query_param,
              data: data,
              success: function(data, status, xhr) {
                $("#_thumbnail_feedbacks").find('.modal-title').text('{% trans "Save Geo Limit" %}');
                $("#_thumbnail_feedbacks").find('.modal-body').html('{% trans "<p>Geometry <strong>successfully</strong> saved!</p><p>To apply them you will need to click on <strong>Apply Changes</strong> button.</p>" %}');
                $("#_thumbnail_feedbacks").modal("show");
              },
              error: function(xhr, status, error) {
                $("#_thumbnail_feedbacks").find('.modal-title').text('{% trans "Save Geo Limit" %}');
                $("#_thumbnail_feedbacks").find('.modal-body').html('{% trans "<p><strong>Error</strong> while trying to save the Geometry!</p>" %}');
                $("#_thumbnail_feedbacks").modal("show");
              }
            });
            return false;
          }
        });
      }

      $(document).on('click', '.serialize-geo-limit', function() {
        serializeGeoLimit($(this).attr('id'));
      });

      function deserializeGeoLimit(ID) {
        $("#confirmMsgBoxModalOK").find('.modal-title').html('{% trans "Load Geo Limits" %}');
        $("#confirmMsgBoxModalOK").find('.modal-body').html('{% trans "<p>This will remove the Geo Limits currently drawn on the map.</p><p>In order to store the Geo Limits you will need to <strong>save</strong> them anyway.</p><p>Do you want to proceed?</p>" %}');
        $("#confirmMsgBoxModalOK_control_field").val('deserializeGeoLimit');
        $('#confirmMsgBoxModalOK').find('.modal-footer .confirm').remove();
        var confirm_button = $('<button />').attr({ type: 'button', id:'confirm_deserializeGeoLimit', class:'btn btn-danger confirm' });
        $('#confirmMsgBoxModalOK').find('.modal-footer').append(confirm_button);
        $("#confirmMsgBoxModalOK").modal("show");
        $('#confirm_deserializeGeoLimit').html('{% trans "OK" %}');
        $('#confirm_deserializeGeoLimit').prop('value', '{% trans "OK" %}');

        $('#confirm_deserializeGeoLimit').on('click', function(e) {
          e.stopImmediatePropagation();
          if ($("#confirmMsgBoxModalOK_control_field").val() == 'deserializeGeoLimit') {
            $("#confirmMsgBoxModalOK_control_field").val();
            $("#confirmMsgBoxModalOK").modal("hide");

            var in_options = {
              'internalProjection': map.projection,
              'externalProjection': new OpenLayers.Projection("EPSG:4326")
            };
            var wkt = new OpenLayers.Format.WKT(in_options);

            var query_param = "";
            if(ID.startsWith("user-load")) {
              query_param = "user_id=" + ID.substring("user-load".length);
            } else if(ID.startsWith("group-load")) {
              query_param = "group_id=" + ID.substring("group-load".length);
            }

            $.ajax({
              type: "GET",
              url: '{% url "resource_geolimits" resource.id %}?' + query_param,
              success: function(data, status, xhr) {
                var features = wkt.read(data);
                var bounds;
                if(features) {
                    if(features.constructor != Array) {
                        features = [features];
                    }
                    for(var i=0; i<features.length; ++i) {
                        if (!bounds) {
                            bounds = features[i].geometry.getBounds();
                        } else {
                            bounds.extend(features[i].geometry.getBounds());
                        }

                    }
                    vectors.removeAllFeatures();
                    vectors.addFeatures(features);
                    map.zoomToExtent(bounds);
                } else {
                    element.value = 'Bad input ' + type;
                }
                return;
              },
              error: function(xhr, status, error) {
                $("#_thumbnail_feedbacks").find('.modal-title').text('{% trans "Load Geo Limit" %}');
                $("#_thumbnail_feedbacks").find('.modal-body').html('{% trans "<p><strong>No Geometry</strong> found!</p>" %}');
                $("#_thumbnail_feedbacks").modal("show");
              }
            });
            return false;
          }
        });
      }

      $(document).on('click', '.deserialize-geo-limit', function(event) {
        console.log($(this).attr('id'));
        deserializeGeoLimit($(this).attr('id'));
      });

      function deleteGeoLimit(ID) {
        $("#confirmMsgBoxModalOK").find('.modal-title').html('{% trans "Delete Geo Limits" %}');
        $("#confirmMsgBoxModalOK").find('.modal-body').html('{% trans "<p>This will <strong>permanently</strong> remove the Geo Limits from the DB.</p><p>To apply them you will need to click on <strong>Apply Changes</strong> button.</p><p>Do you want to proceed?</p>" %}');
        $("#confirmMsgBoxModalOK_control_field").val('deleteGeoLimit');
        $('#confirmMsgBoxModalOK').find('.modal-footer .confirm').remove();
        var confirm_button = $('<button />').attr({ type: 'button', id:'confirm_deleteGeoLimit', class:'btn btn-danger confirm' });
        $('#confirmMsgBoxModalOK').find('.modal-footer').append(confirm_button);
        $("#confirmMsgBoxModalOK").modal("show");
        $('#confirm_deleteGeoLimit').html('{% trans "OK" %}');
        $('#confirm_deleteGeoLimit').prop('value', '{% trans "OK" %}');

        $('#confirm_deleteGeoLimit').on('click', function(e) {
          e.stopImmediatePropagation();
          if ($("#confirmMsgBoxModalOK_control_field").val() == 'deleteGeoLimit') {
            $("#confirmMsgBoxModalOK_control_field").val();
            $("#confirmMsgBoxModalOK").modal("hide");

            var query_param = "";
            if(ID.startsWith("user-remove")) {
              query_param = "user_id=" + ID.substring("user-remove".length);
            } else if(ID.startsWith("group-remove")) {
              query_param = "group_id=" + ID.substring("group-remove".length);
            }

            $.ajax({
              type: "DELETE",
              url: '{% url "resource_geolimits" resource.id %}?' + query_param,
              success: function(data, status, xhr) {
                $("#_thumbnail_feedbacks").find('.modal-title').text('{% trans "Delete Geo Limit" %}');
                $("#_thumbnail_feedbacks").find('.modal-body').html('{% trans "<p><strong>Geo Limitsy</strong> successfully deleted!</p>" %}');
                $("#_thumbnail_feedbacks").modal("show");

                vectors.removeAllFeatures();
                return;
              },
              error: function(xhr, status, error) {
                $("#_thumbnail_feedbacks").find('.modal-title').text('{% trans "Delete Geo Limit" %}');
                $("#_thumbnail_feedbacks").find('.modal-body').html(
                  "{% trans '<p><strong>Error</strong> occurred while trying to delete Geo Limits:</p>' %}" + '<q>' + xhr.responseText + '</q>');
                $("#_thumbnail_feedbacks").modal("show");
              }
            });
            return false;
          }
        });
      }

      $(document).on('click', '.delete-geo-limit', function() {
        deleteGeoLimit($(this).attr('id'));
      });
    }
  });
</script>
{% endif %}
